package com.liusha.quicksand.interceptor;//package com.liusha.quicksand.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 一世长安一世欢
 * @Date: 2020/10/27
 * @Time: 0:53
 * @Description: No Description
 */
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 在请求被处理之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 检查每个到来的请求对应的session域中是否有登录标识
//        Object loginName=request.getSession().getAttribute("user");
//        if (null==loginName||!(loginName instanceof String)){
//            // 未登录，重定向到登录页
//
//            response.sendRedirect("/login");
//            return false;
//        }
//
//        String userName = (String) loginName;
//        System.out.println("当前用户已登录，登录的用户名为： " + userName);
//        return true;

        if (request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }

    /**
     * 在请求被处理后，视图渲染之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束后调用
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
